package com.cl.web.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.cl.bean.Dept;
import com.cl.service.DeptService;
import com.cl.utils.PageBean;
import com.cl.web.base.BaseAction;

import net.sf.json.JSONObject;

@Controller
@Scope("prototype")
public class DeptAction extends BaseAction<Dept>{
	
	@Autowired
	private DeptService deptService;
	
	public String add(){
		deptService.save(model);
		return LIST;
	}
	
	public String findByName() throws IOException{
		String name = model.getP_name();
		int count = deptService.findByName(name);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=utf-8");
		PrintWriter pw = response.getWriter();
		JSONObject json = new JSONObject();
		if(count == 0){
			json.put("result", "ok");
			pw.println(json.toString());
		}else{
			json.put("result", "notok");
			pw.println(json.toString());
		}
		return NONE;
	}
	
	public String getByName() throws IOException{
		List<Dept> dept = deptService.getAllName();
		ListToJson(dept, new String[]{});
		return NONE;
	}
	
	public String findByPage() throws IOException{
		dc.add(Restrictions.eq("p_is", "1"));
		PageBean pb = deptService.getPageBean(dc,page,limit);
		ObjectToJson(pb);
		return NONE;
	}
	
	public String findByPage1() throws IOException{
		dc.add(Restrictions.eq("p_is", "0"));
		PageBean pb = deptService.getPageBean(dc,page,limit);
		ObjectToJson(pb);
		return NONE;
	}
	
	public String update_findById(){
		Dept dept = deptService.findById(model.getP_id());
		ServletActionContext.getRequest().getSession().setAttribute("dept", dept);
		return "update";
	}
	
	public String update(){
		Dept dept = deptService.findById(model.getP_id());
		dept.setP_name(model.getP_name());
		dept.setP_remark(model.getP_remark());
		deptService.update(dept);
		return NONE;
	}
	
	public String del(){
		deptService.del(model.getP_id());
		return LIST;
	}
	
	public String restore(){
		deptService.restore(model.getP_id());
		return "restore";
	}
}
